package charles.testproject.sipmessages;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SipMessageRegister {
	String host="192.168.2.31";
	  int port=5060;
	  DatagramSocket socket;
	  
	  public void createSocket()throws Exception{
		  InetAddress inetAdrr = InetAddress.getByName(host);
	       socket=new DatagramSocket(port,inetAdrr);
	  }
	  

	  public void communicate()throws Exception{
	    StringBuffer sb=new StringBuffer("REGISTER sip:ims.nsn.com SIP/2.0\r\n");
	    sb.append("Via: SIP/2.0/UDP 192.168.2.169:5060;branch=z9hG4bK5bf696b4a47896fd50bbe6c6f02aec1a\r\n");
	    sb.append("To:" + " j2se06 " + "sip:j2se06@ims.nsn.com\r\n");
	    sb.append("From:" + " j2se06 " + "sip:j2se06@ims.nsn.com>;tag=cc5e795b\r\n");
	    sb.append("CSeq: 1 REGISTER\r\n");
	    sb.append("Call-ID: 0a3e2fcf5fb2c2603e97c2fcfd464157@0.0.0.0\r\n\r\n");
	    
	    System.out.println(sb.toString());
	    byte[] b = new byte[128];
	    DatagramPacket dataPaket = new DatagramPacket(b, b.length);
	    
	    
//	    //发出HTTP请求
//	    OutputStream socketOut=socket.getOutputStream();
//	    socketOut.write(sb.toString().getBytes());
//	    socket.shutdownOutput();  //关闭输出流
//	       
//	    //接收响应结果
//	    InputStream socketIn=socket.getInputStream();
//	    ByteArrayOutputStream buffer=new ByteArrayOutputStream();
//	    byte[] buff=new byte[1024];  
//	    int len=-1;
//	    while((len=socketIn.read(buff))!=-1){
//	      buffer.write(buff,0,len);
//	    }
//	   
//	    System.out.println(new String(buffer.toByteArray()));  //把字节数组转换为字符串


	/*
	    InputStream socketIn=socket.getInputStream();
	    BufferedReader br=new BufferedReader(new InputStreamReader(socketIn));
	    String data;
	    while((data=br.readLine())!=null){
	      System.out.println(data);
	    }
	*/        
	    socket.close();
	  }
	  
	  public static void main(String args[])throws Exception{
		  SipMessageRegister client=new SipMessageRegister();
	    client.createSocket();
	    client.communicate();
	  } 

}
